<script setup lang="ts">
import { reactive, ref } from 'vue';
import { getCurrentInstance, showModal, showToast } from '@tarojs/taro';
import JSEncrypt from 'jsencrypt';
import { cloneDeep } from 'lodash';
import { setStorage, setStorageSync, reLaunch, showLoading, hideLoading } from '@tarojs/taro';
import IMG_BLUE_BG from '/@/assets/image/bg/blue-bg.png';
import { APP_EDITION } from '/@/common/constant';
import { USER_LOGIN, SEND_LOGIN_SMS } from '/@/api/modules/base/user';
import { GET_PUBLIC_KEY } from '/@/api/modules/open-api/auth';
import { formRules } from './state';

const loginPhoneFormRef = ref();
const RSA = new JSEncrypt();

/**
 * @description 当前路由信息
 */
const params = getCurrentInstance().router?.params as {
  /**
   * 前往页面
   */
  toPage?: string;
};

const state = reactive<{
  /**
   * 获取验证码按钮文本
   */
  getCodeBtnText: string;
  /**
   * 获取验证码按钮文本
   */
  isDisabledByGetCodeBtn: boolean;
  /**
   * 应用版本
   */
  appEdition: keyof typeof APP_EDITION;
  /**
   * taro应用环境
   */
  taroEnv: string;
}>({
  getCodeBtnText: '点击获取',
  isDisabledByGetCodeBtn: false,
  appEdition: (process.env.APP_EDITION as keyof typeof APP_EDITION) || 'default',
  taroEnv: process.env.TARO_ENV,
});

const formState = reactive<BaseUserLoginApi.UserLoginReq>({
  account: '',
  password: '',
  loginType: 2,
});

/**
 * 获取验证码校验倒计时
 * @param val -时间值
 */
function timeOutByGetCode(val: number) {
  if (val > 0) {
    const newVal = val - 1;

    state.isDisabledByGetCodeBtn = true;
    state.getCodeBtnText = `${newVal}s`;
    setTimeout(() => {
      timeOutByGetCode(newVal);
    }, 1000);
  } else {
    state.isDisabledByGetCodeBtn = false;
    state.getCodeBtnText = '点击获取';
  }
}

/**
 * 获取短信验证码
 * @param phoneNum
 */
function getCode(phoneNum: string) {
  if (!/^1\d{10}$/.test(phoneNum)) {
    showToast({
      icon: 'error',
      title: '请输入正确的手机号',
    });
    return;
  }

  SEND_LOGIN_SMS({
    account: phoneNum,
  }).then((res) => {
    timeOutByGetCode(60);
    showToast({ title: res.comResp.msg || '获取验证码成功!' });
  });
}

/**
 * @function 确认登录
 */
function submit() {
  loginPhoneFormRef.value.validate().then(({ valid }) => {
    if (!valid) return;
    showLoading();

    GET_PUBLIC_KEY({ secretTag: 'ib_platform_pub' }).then((res1) => {
      const _form = cloneDeep(formState);
      RSA.setPrivateKey(res1.publicKey);
      _form.password = RSA.encrypt(`${Date.now()}${formState.password}`) as string;

      USER_LOGIN(_form)
        .then((res) => {
          setStorage({
            key: 'token',
            data: res.token,
            success: () => {
              formState.account = '';
              formState.password = '';
              setStorageSync('loginType', 'default');
              hideLoading();
              reLaunch({
                url: params.toPage ? decodeURIComponent(params.toPage) : '/pages/index/index',
              });
            },
          });
        })
        .catch((err) => {
          hideLoading();
          showModal({
            content: err.comResp.tip,
            showCancel: false,
          });
        });
    });
  });
}
</script>

<template>
  <view class="user-login-phone app-page--1">
    <view class="user-login-phone__header">
      <view class="user-login-phone__header__container">
        <view class="user-login-phone__title">欢迎使用，</view>
        <view class="user-login-phone__title--sub">
          {{
            {
              default: '航天云筑智慧医院后勤',
              hgy: '慧管用保障平台',
              'jinhua-police-service': '掌上运维管理',
              'can-nang-third-hospital': '航天云筑智慧医院后勤',
            }[state.appEdition]
          }}
        </view>
      </view>
      <image class="user-login-phone__header-bg" mode="widthFix" :src="IMG_BLUE_BG" />
    </view>
    <view class="user-login-phone__wrapper">
      <nut-form
        :model-value="formState"
        :rules="formRules"
        class="user-login-phone__form"
        ref="loginPhoneFormRef"
      >
        <view class="user-login-phone__form-item-label">手机号</view>
        <nut-form-item prop="account" error-message-align="left">
          <nut-input
            v-model="formState.account"
            placeholder="请输入手机号"
            type="text"
            clearable
            show-word-limit
            max-length="11"
          />
        </nut-form-item>
        <view class="user-login-phone__form-item-label">验证码</view>
        <nut-form-item
          class="user-login-phone__form-item-password-wrapper"
          prop="password"
          error-message-align="left"
        >
          <view class="user-login-phone__password-wrapper">
            <nut-input
              v-model="formState.password"
              placeholder="请输入验证码"
              type="text"
              clearable
              show-word-limit
              max-length="6"
            >
              <template #right>
                <nut-button
                  class="user-login-phone__get-code-btn"
                  size="small"
                  :disabled="state.isDisabledByGetCodeBtn"
                  @click="getCode(formState.account)"
                >
                  {{ state.getCodeBtnText }}
                </nut-button>
              </template>
            </nut-input>
          </view>
        </nut-form-item>
      </nut-form>
      <nut-button class="user-login-phone__login-btn" type="info" block @click="submit()">
        登录
      </nut-button>
      <view class="user-login-phone__to-other-login-wrapper">
        <view class="user-login-phone__to-other-login-wrapper--left">
          <text
            @click="
              reLaunch({
                url: `/pages/user/login/index?toPage=${params.toPage || '/pages/index/index'}`,
              })
            "
          >
            用户名密码登录
          </text>
        </view>
        <view class="user-login-phone__to-other-login-wrapper--right">
          <text
            @click="
              reLaunch({
                url: `/pages/user/login-now/index?toPage=${params.toPage || '/pages/index/index'}`,
              })
            "
          >
            使用一键登录
          </text>
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss">
@import './index.scss';
</style>
